package io.renren.modules.generator.controller;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.generator.entity.ProjectFileEntity;
import io.renren.modules.generator.service.ProjectFileService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * @author author
 * @email author@gmail.com
 * @date 2021-07-03 10:02:54
 */
@RestController
@RequestMapping("generator/projectfile")
public class ProjectFileController {
    @Autowired
    private ProjectFileService projectFileService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:projectfile:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = projectFileService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:projectfile:info")
    public R info(@PathVariable("id") Integer id) {

        ProjectFileEntity projectFile = projectFileService.getById(id);

        return R.ok().put("projectFile", projectFile);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("generator:projectfile:save")
    public R save(@RequestParam(value = "files") List<MultipartFile> files, @RequestParam String obj, HttpServletRequest request) {
        try {
            //创建文件在服务器端存放路径
            String fileDir = "static/upload/";
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            File upload = new File(path.getAbsolutePath(), fileDir);
            if (!upload.exists()) {
                upload.mkdirs();
            }
            JSONObject jsonObject = JSONObject.parseObject(obj);
            Integer id = jsonObject.getInteger("id");
            //生成文件在服务器端存放的名字
            for (int i = 0; i < files.size(); i++) {
                String fileSuffix = files.get(i).getOriginalFilename().substring(files.get(i).getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID() + fileSuffix;

                File file = new File(upload + "/" + fileName);
                //上传
                FileUtils.copyInputStreamToFile(files.get(i).getInputStream(), file);

                ProjectFileEntity projectFile = new ProjectFileEntity();
                projectFile.setProjectId(id);
                projectFile.setFileOriginName(files.get(i).getOriginalFilename());
                projectFile.setFileStorageName(file.getName());

                projectFileService.save(projectFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ProjectFileEntity projectFile) {
        projectFileService.updateById(projectFile);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids) {
        projectFileService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 删除单条附件
     * @param id
     * @return
     */
    @RequestMapping("/deleteSingle/{id}")
    @RequiresPermissions("generator:projectfile:deleteSingle")
    public R deleteSingle(@PathVariable("id") Integer id) {
        projectFileService.removeById(id);

        return R.ok();
    }

}
